﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using ShareB.Models;

namespace ShareB.Controllers
{

    [HandleError]
    public class UserController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }
        public PublicationService _publicationService { get; set; }
        FollowerService _followerService;



        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new UserMembershipService(); }
            if (_followerService == null) { _followerService = new FollowerService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // GET
        // URL: /User/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        // **************************************
        // POST
        // URL: /User/LogOn
        // **************************************

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /User/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // GET
        // URL: /User/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        // **************************************
        // POST
        // URL: /User/Register
        // **************************************

        [HttpPost]
        public ActionResult Register(RegisterModel model, HttpPostedFileBase myFile)
        {

            model.Photograph = myFile;
            if (ModelState.IsValid)
            {
                //validate file uploaded
                if (model.Photograph != null && model.Photograph.ContentType.ToLower().StartsWith("image") == false)
                {
                    ModelState.AddModelError("", "The provided file isnt a compatible image.");
                }
                else {
                    // Attempt to register the user
                    MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email, model.FirstName, model.LastName, model.Address, model.Photograph);

                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("", UserValidation.ErrorCodeToString(createStatus));
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // Get
        // URL: /User/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        // **************************************
        // Post
        // URL: /User/ChangePassword
        // **************************************
        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /User/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        // **************************************
        // GET
        // URL: /User/Profile
        // **************************************
        public ActionResult Profile()
        {
            //preencher o modelo a fazer display
            ProfileModel model = MembershipService.GetProfile(HttpContext.User.Identity.Name);
            return View(model);
        }


        // **************************************
        // GET
        // URL: /User/EditProfile
        // **************************************
        public ActionResult EditProfile()
        {
            //preencher o modelo a fazer display
            ProfileModel model = MembershipService.GetProfile(HttpContext.User.Identity.Name);
            return View(model);
        }


        // **************************************
        // POST
        // URL: /User/EditProfile
        // **************************************
        [HttpPost]
        public ActionResult EditProfile(ProfileModel model)
        {
            //preencher o modelo a fazer display
            if (ModelState.IsValid)
            {
                MembershipService.EditUser(model);
                return RedirectToAction("Profile");
            }
            else ModelState.AddModelError("", "An error as ocurred");    
            return View(model);

        }

        // **************************************
        // GET
        // URL: /User/ManageFollowers
        // **************************************
        public ActionResult ManageFollowers()
        {
            //preencher o modelo a fazer display
            int userID = MembershipService.GetUserID(HttpContext.User.Identity.Name);
            RelationsModel model = _followerService.LoadFollowers(userID);
            return View(model);
        }

        // **************************************
        // GET
        // URL: /User/AddPublishers
        // **************************************
        public ActionResult AddPublishers(string id)
        {
            _followerService.AddPublishers(MembershipService.GetUserID(HttpContext.User.Identity.Name), Convert.ToInt32(id));
            return RedirectToAction("ManageFollowers");
        }


        // **************************************
        // GET
        // URL: /User/RemovePublishers
        // **************************************
        public ActionResult RemovePublishers(string id)
        {
            _followerService.RemovePublishers(Convert.ToInt32(id), MembershipService.GetUserID(HttpContext.User.Identity.Name));
            return RedirectToAction("ManageFollowers");
        }

        // **************************************
        // GET
        // URL: /User/SearchPublishers
        // **************************************
        public ActionResult SearchPublishers(string searchValue)
        {            
            return View(_followerService.SearchPublishers(searchValue));
        }

        // **************************************
        // GET
        // URL: /User/ListPublishers
        // **************************************
        public ActionResult ListPublishers()
        {
            return View(_followerService.ViewPublishers(MembershipService.GetUserID(HttpContext.User.Identity.Name)));
        }

        // **************************************
        // GET
        // URL: /User/ViewPublisherByID
        // **************************************
        public ActionResult ViewPublisherByID(string id)
        {
            ProfilePublishersModel model = new ProfilePublishersModel();
            model = MembershipService.GetProfilePublishers(Convert.ToInt32(id));

            return View(model);
        }


        // **************************************
        // GET
        // URL: /User/ViewPublisherPublication
        // **************************************
        public ActionResult ViewPublisherPublication(string id)
        {
            _publicationService = new PublicationService();
            PublicationModel model = new PublicationModel();
            model = _publicationService.GetMyPublication(Convert.ToInt32(id));

            return View(model);
        }

        // **************************************
        // GET
        // URL: /User/ViewPublisherPublicationTemp
        // **************************************
        public ActionResult ViewPublisherPublicationTemp(PublicationModel model)
        {
            _publicationService = new PublicationService();
            _publicationService.ActClassification(model);

            return RedirectToAction("ViewPublisherPublication", new { id = model.PublicationID });

            //bool flag = false;
            //_publicationService = new PublicationService();
            //foreach (ClassificationModel a in _publicationService.GetClassificationByID(model.PublicationID))
            //{
            //    model.Classif.Add(a);
            //}

            //if (model.ClassifAlone != null)
            //{
            //    if (model.ClassifAlone.Classification != 0)
            //    {
            //        model.ClassifAlone.PublicationID = model.PublicationID;
            //        model.ClassifAlone.UserID = MembershipService.GetUserID(HttpContext.User.Identity.Name);

            //        for (int i = 0; i < model.Classif.Count; i++)
            //        {
            //            if (model.ClassifAlone.UserID == model.Classif[i].UserID)
            //            {
            //                // JA ESTA INSERIDO, TEMOS QUE FAZER UM UPDATE À BASE DE DADOS
            //                _publicationService.UpdateClassification(model.ClassifAlone, model.Classif[i]);
            //                flag = true;
            //                break;
            //            }
            //        }

            //        if (!flag)
            //        {
            //            _publicationService.AddClassification(model.ClassifAlone);
            //        }

            //    }
            //}

            //model.Classif = _publicationService.GetClassificationByID(model.PublicationID);
            //return View(model);
        }
    }
}
